package com.grgbanking.encryp.netty.server.handler;

import com.grgbanking.encryp.service.BusinessLogic;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@ChannelHandler.Sharable
@Slf4j
public class TcpServerHandler extends SimpleChannelInboundHandler<String> {
    @Autowired
    private BusinessLogic businessLogic;
    private final ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String msg) {
        System.out.println("Thread name : "+ Thread.currentThread().getName());
        // 提交任务到线程池异步处理
        executorService.submit(() -> {
            try {
                System.out.println("executorService  Thread name : "+ Thread.currentThread().getName());
                log.info("Received message: " + msg);
                String response = businessLogic.process(msg);
                log.info("Sending response: " + response);
                ctx.writeAndFlush(response).addListener(future -> {
                    if (!future.isSuccess()) {
                        log.error("Failed to send response:" + response);
                    }
                });
            } catch (Exception e) {
                ctx.close();
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        System.out.println("Error occurred in TCP server handler");
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Channel inactive."+ctx.channel().remoteAddress());
        super.channelInactive(ctx);
    }
}

